package com.common.base.manager

import com.common.base.bean.ConfigBean
import com.common.base.tools.utils.JsonUtils
import com.common.base.tools.utils.file.FileUtil
import com.common.base.tools.utils.file.StorageEnum
import com.common.base.tools.utils.logger
import java.io.File
import java.lang.Exception

/**
 * 三疯
 * *************************
 *
 * *************************
 */
object ConfigManager {
    var configBean: ConfigBean? = null
    init {
        readConfig()
    }

    /**
     * 保存配置
     * [ConfigBean]
     */
    fun saveConfig(configBean: ConfigBean) {
        this.configBean = configBean
        val fileDir = FileUtil.createFileDir(StorageEnum.STORAGE_DATA_FILES, "config")
        fileDir?.path?.let {
            val file = FileUtil.createFile(it, "config")
            file?.let { it1 -> FileUtil.writeFile(it1, JsonUtils.toJson(configBean)) }
        }
    }

    /**
     * 读取配置
     * [ConfigBean]
     */
    fun readConfig(): ConfigBean? {
        val file = File("${FileUtil.getStorePath(StorageEnum.STORAGE_DATA_FILES)}/config/config")
        configBean = if (file.exists()) {
            try {
                JsonUtils.fromJson(FileUtil.readFile(file), ConfigBean::class.java)
            } catch (e: Exception) {
                logger.error("文件解析异常", e)
                null
            }
        } else {
            logger.error("读取配置文件不存在")
            null
        }
        return configBean
    }
}